package com.rxb.blog.job;

import com.rxb.blog.mapper.ArticlePictureMapper;
import com.rxb.blog.utils.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Author：rxb
 * Date：2020-03-11 21:20
 * Description：<描述>
 */
@Component
public class TaskService {

    @Autowired
    private ArticlePictureMapper articlePictureMapper;

    /**
     * 定时任务 --处理 上传的 无效  图片（没有用的） http://localhost:9081/blog_front/images\2f4d9f8f47064bc3ae094d6655ba642a.png
     */
    @Scheduled(cron = "0 0 3 * * ?")    //每天凌晨3点执行
    public void deleteUnUsePic(){
        System.out.println("定时清理图片开始");
        List<String> pics =  articlePictureMapper.getAllPicUrls();
        List<String> picsBack = new ArrayList<>();
                pics.forEach(pic ->{
            String substring = pic.substring(pic.lastIndexOf(File.separator)+1, pic.length());
            System.out.println(substring);
            picsBack.add(substring);
        });

        List<String> picPath = new ArrayList<>();
        List<String> picPathBack = new ArrayList<>();

        FileUtil.getAllFileName("C:\\Users\\rxb\\Desktop\\img",picPath);
        picPath.forEach(pic ->{
            String substring = pic.substring(pic.lastIndexOf(File.separator)+1, pic.length());
            picPathBack.add(substring);
        });

        //  picPathBack - picsBack (差集)
        picPathBack.removeAll(picsBack);
        // 删除 无效图片
        picPathBack.forEach(path->{
            String deletePicPath = "C:\\Users\\rxb\\Desktop\\img\\"+ path;
            FileUtil.deleteFile(deletePicPath);
        });

        System.out.println("定时清理图片结束");
    }


}
